/*
 * @Author: hongbin
 * @Date: 2021-11-12 14:33:50
 * @LastEditors: hongbin
 * @LastEditTime: 2021-11-13 12:15:37
 * @Description:按住拉长组件 操作dom
 */
import { FC, memo, ReactElement, MouseEventHandler, useRef } from "react";
import styled from "styled-components";

interface IProps {}

const ElongateLine: FC<IProps> = (): ReactElement => {
  const ref = useRef<HTMLDivElement>(null);

  const onMouseMove: MouseEventHandler<HTMLDivElement> = ({ pageX }) => {
    const target = ref.current as HTMLDivElement;
    const prevW = Number(target.getAttribute("prevW"));
    const prevX = Number(target.getAttribute("prevX"));
    target.style["width"] = prevW + pageX - prevX + "px";
  };

  const onMouseUp: MouseEventHandler<HTMLDivElement> = e => {
    // @ts-ignore
    document.removeEventListener("mousemove", onMouseMove);
    // @ts-ignore
    document.removeEventListener("mouseup", onMouseUp);
    // @ts-ignore
    document.removeEventListener("mouseleave", onMouseUp);
    ref.current!.style["cursor"] = "default";
  };

  const onMouseDown: MouseEventHandler<HTMLDivElement> = ({
    currentTarget,
    pageX,
  }) => {
    const parent = currentTarget.parentNode as HTMLDivElement;
    parent.setAttribute("prevW", parent.offsetWidth.toString());
    parent.setAttribute("prevX", pageX.toString());
    parent.style["cursor"] = "ew-resize";
    // @ts-ignore
    !ref.current && (ref.current = parent);

    //@ts-ignore
    document.addEventListener("mousemove", onMouseMove);
    //@ts-ignore
    document.addEventListener("mouseup", onMouseUp);
    //@ts-ignore
    document.addEventListener("mouseleave", onMouseUp);
  };

  return <Line onMouseDown={onMouseDown} />;
};

export default memo(ElongateLine);

const Line = styled.div`
  position: absolute;
  top: 0;
  right: 0;
  width: 5px;
  height: 100%;
  cursor: ew-resize;
`;
